package com.hx.ycy.web.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicLong;

public class LoggingInterceptor extends HandlerInterceptorAdapter {

    private static final String XXID = "xxxx";
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class);
    private AtomicLong counter = new AtomicLong();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        request.setAttribute(XXID, counter.incrementAndGet());
        logRequest(request);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        LOGGER.info("\nResponse {}:\n\tstatus: {}",
                request.getAttribute(XXID),
                response.getStatus());
    }

    private void logRequest(HttpServletRequest request) {
        LOGGER.info("\nRequest {}:\n\t" +
                        "url: {}\n\t" +
                        "queryString: {}\n\t" +
                        "method: {}",
                request.getAttribute(XXID), request.getRequestURL(), request.getQueryString(), request.getMethod());
        LOGGER.info("Request header:");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            LOGGER.info("\t{}:{}", headerName, request.getHeader(headerName));
        }
    }
}
